package com.bodystm.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.persistence.EnumType;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bodystm.algorithm.DllInterface;
import com.bodystm.bean.Bed;
import com.bodystm.bean.BedUseStatus;
import com.bodystm.bean.Patient;
import com.bodystm.bean.PatientBedUser;
import com.bodystm.bean.PatientEquip;
import com.bodystm.bean.Temperature;
import com.bodystm.bean.datadeal.BodystmProduct;
import com.bodystm.bean.datadeal.EcgAnalysis;
import com.bodystm.bean.datadeal.EcgAnalysis.EcgChannel;
import com.bodystm.config.PublicSetting;
import com.bodystm.dao.PatientBedDao;
import com.bodystm.manager.DataHandlerManager;
import com.bodystm.service.BedService;
import com.bodystm.service.PatientBedService;
import com.bodystm.service.PatientEquipService;
import com.bodystm.service.PatientService;
import com.bodystm.service.TemperatureService;
import com.bodystm.system.SystemSetting;
import com.bodystm.system.SystemSettingService;
import com.bodystm.web.DeviceSettings;
import com.bodystm.web.EasyUiMessage;
import com.bodystm.web.TemperatureDevice;
import com.mimosa.common.system.user.TUser;
import com.mimosa.common.system.user.UserContext;
import com.mimosa.common.system.user.UserService;
import com.mimosa.util.config.Page;

@Controller
@RequestMapping("/bed")
public class BedController {
	@Resource
	private BedService bedService;

	@Resource
	private PatientService patientService;

	@Resource 
	private UserService userService;
	
	@Resource
	private TemperatureService temperatureService;
	
	@Autowired
	private PatientBedService patientBedUserService;

	@Autowired
	private PatientBedDao patientBedUserDao;
	@Autowired
	private SystemSettingService systemSettingService;
	@Autowired
	private PatientEquipService patientEquipService;
	/**
	 * 床位监测页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/index")
	public String degreelisten(HttpSession session,Model model){
		SystemSetting systemSetting=systemSettingService.getSystemSetting();
		if(systemSetting!=null){
			model.addAttribute("logoPath", systemSetting.getHospitalLogoPath());
		}
//		List<Bed> lstBed=this.bedService.findList("from Bed t where t.user.id=? and t.usable=1 order by (t.name+0) ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
		List<Bed> lstBed=this.bedService.findList("from Bed t where t.usable=1 order by (t.name+0) ASC");
		model.addAttribute("bedList", lstBed);
		model.addAttribute("showPulseOrHr", PublicSetting.ShowPulseOrHeartRate);
		if (DeviceSettings.hasBeds.size()<lstBed.size()) {
			for (Bed bed : lstBed) {
				if (bed.getConcentratorNo()!=null&&!DeviceSettings.hasBeds.containsKey(bed.getConcentratorNo())) {
					DeviceSettings.hasBeds.put(bed.getConcentratorNo(), bed);
				}
			}
		}
		if (PublicSetting.ifMeasureScreen) {
			model.addAttribute("deviceCaps", DllInterface.INSTANCE.GetDeviceCaps4Bodystm_EX(4));
			model.addAttribute("deviceCapsHeight", DllInterface.INSTANCE.GetDeviceCaps4Bodystm_EX(6));
		}
		model.addAttribute("websocketUrl", PublicSetting.websocketUrl);
		/*if (DeviceSettings.lstBeds.size()==0) {
			DeviceSettings.lstBeds=lstBed;
		}*//*else {//为了保持后台床位临时增减时保持数据一致性，就不需要重启服务器了
			int i=0;
			for (Bed bed : lstBed) {
				for(;i<DeviceSettings.lstBeds.size();i++){
					if (bed.getId().equals(DeviceSettings.lstBeds.get(i).getId())) {
						break;
					}else{
						DeviceSettings.lstBeds.
					}
				}
			}
			
		}*/
		return "bed/index";
	}
	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/degreelisten2.action")
	public String degreelisten2(Model model){
		SystemSetting systemSetting=systemSettingService.getSystemSetting();
		if(systemSetting!=null){
			model.addAttribute("logoPath", systemSetting.getHospitalLogoPath());
		}
		return "bed/index_bak";
	}
	@RequestMapping("/degreelisten4Admin.action")
	public String degreelisten4Admin(){
		return "bed/degreelisten";
	}	
	/**
	 * 添加床位页面
	 * @return
	 */
	@RequestMapping("/addBed.action")
	public String addBed(HttpSession session,Model model){
		List<Bed> lstBed=null;
		lstBed=this.bedService.findList("from Bed t where t.user.id=? and t.usable=1 order by (t.name+0) ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
//		DeviceSettings.lstBeds=lstBed;
    	/*if (DeviceSettings.lstBeds.size()==0) {
    		lstBed=this.bedService.findList("from Bed t where t.user.id=? and t.usable=1 order by (t.name+0) ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
    		DeviceSettings.lstBeds=lstBed;
		}else{
			lstBed=DeviceSettings.lstBeds;
		}*/
    	model.addAttribute("bedList", lstBed);
		return "bed/addBed";
	}
	@RequestMapping("/edit.action")
	public String edit(String id, String type, Model model) {
		if (StringUtils.isNotBlank(id)) {
			Bed bed = this.bedService.getEntity(id);
			model.addAttribute("bed", bed.getPatient());
		}
		return "bed/" + type;
	}
	@ResponseBody
	@RequestMapping("/editBed.action")
	public String editBed(String id, String name,String mac, Model model) {
		JSONObject result=new JSONObject();
		result.put("success", false);
		if (StringUtils.isNotBlank(id)) {
			Bed bed = this.bedService.getEntity(id);
			java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.name=? and t.usable=1 order by t.name ASC", name);
			if(lstBed.size()>0&&!lstBed.get(0).getId().equals(id)) return "{\"success\":false,\"msg\":\"床位名称不可重复\"}";
			lstBed=this.bedService.findList("from Bed t where t.concentratorNo=? and t.usable=1 order by t.name ASC", mac);
			if(lstBed.size()>0&&!lstBed.get(0).getId().equals(id)) return "{\"success\":false,\"msg\":\"床位mac地址不可重复\"}";
			if (bed!=null) {
				if (!mac.equals(bed.getConcentratorNo())) {
					//更新DeviceSettings.hasBeds数据
					Bed bedOld=DeviceSettings.hasBeds.get(bed.getConcentratorNo());
					bedOld.setConcentratorNo(mac);
					bedOld.setName(name);
					bedOld.setEcg(null);
					bedOld.setBloodPressure(null);
					bedOld.setOximetry(null);
					DeviceSettings.hasBeds.remove(bed.getConcentratorNo());
					DeviceSettings.hasBeds.put(mac, bed);
//					DeviceSettings.hasBeds.put(mac, bedOld);
				}
				
				bed.setName(name);
				bed.setConcentratorNo(mac);
				bedService.saveEntity(bed);
				result.put("success", true);
			}
		}
		return result.toString();
	}
	
	/**
	 * 获取所有异常设备（上数但是未使用状态，没有对应的床位和病人）
	 * @return
	 */
	@RequestMapping("/listExpMacs.action")
	@ResponseBody
	public String listExpMacs(){
		JSONObject jSONObject=new JSONObject();
		//DeviceSettings.lstMacs4NoPatients.add("ABCD");
		jSONObject.put("expmacs", DeviceSettings.lstMacs4NoPatients.toArray());
		return jSONObject.toString();
	}
	@RequestMapping("/delExpMac.action")
	@ResponseBody
	public String delExpMac(String mac){
		JSONObject jSONObject=new JSONObject();
		if (DeviceSettings.lstMacs4NoPatients.contains(mac)) {
			DeviceSettings.lstMacs4NoPatients.remove(mac);
		}
		return "{success:true}";
	}
	
	/*
	 * 获取所有部门
	 */
	@RequestMapping("/listDepartments.action")
	@ResponseBody
	public String listDepartments(){
		List<TUser> users=this.userService.getAll();
		JSONObject bedJSONObject=null;
		JSONArray jSONArray = new JSONArray();
		for(TUser user:users){
			if(user.getUserName().toLowerCase().equals("admin")){
				//users.remove(user);
				continue;
			}
			bedJSONObject = new JSONObject();
			bedJSONObject.put("id", user.getId());
			bedJSONObject.put("name", user.getRealName());
			jSONArray.add(bedJSONObject);
			
		}
		return jSONArray.toString();
	}
	
	@RequestMapping("/getBedsByDepartmentId.action")
	@ResponseBody
	public String getBedsByDepartmentId(String departmentId){
		List<Bed> lstBeds=this.bedService.findList("from Bed t where t.user.id=? and t.status='empty' order by t.name ASC", departmentId);
		JSONObject bedJSONObject=null;
		JSONArray jSONArray = new JSONArray();
		for(Bed bed:lstBeds){
			bedJSONObject = new JSONObject();
			bedJSONObject.put("id", bed.getId());
			bedJSONObject.put("name", bed.getName());
			jSONArray.add(bedJSONObject);
		}
		return jSONArray.toString();
	}
	
	@RequestMapping("/outBed.action")
	@ResponseBody
	public String outBed(String ids, Model model) {
		this.bedService.outBed(ids);
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/save.action")
	public String save(Bed bed) {
		this.bedService.saveEntity(bed);
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		return Boolean.TRUE.toString().toLowerCase();
	}

	/*
	 * 娣诲姞搴婁綅 by rxz 20151124
	 */
	@ResponseBody
	@RequestMapping("/add.action")
	public String add(String bedid,String concentratorNo,HttpSession session) {
//		java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.name=? and t.usable=1 and t.user.id=? order by t.name ASC", bedid,((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
        java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.name=? and t.usable=1 order by t.name ASC", bedid);
		if(lstBed.size()>0) return "{\"success\":false,\"msg\":\"床位名称不可重复\"}";
		lstBed=this.bedService.findList("from Bed t where t.concentratorNo=? and t.usable=1 order by t.name ASC", concentratorNo);
		if(lstBed.size()>0) return "{\"success\":false,\"msg\":\"床位mac地址不可重复\"}";
		Bed bed=new Bed();
		bed.setName(bedid);
		if(concentratorNo!=null&&concentratorNo.length()>0)
		bed.setConcentratorNo(concentratorNo);
		bed.setStatus("empty");
//		bed.setUser((TUser)session.getAttribute(UserContext.USER_ATTR));//20180421 sessionid不能保持所以临时 login filter去掉
		if (session.getAttribute(UserContext.USER_ATTR) != null) {
			bed.setUser((TUser)session.getAttribute(UserContext.USER_ATTR));
		}
		this.bedService.saveEntity(bed);
		//更新DeviceSettings.hasBeds数据
//		DeviceSettings.hasBeds.put(concentratorNo, bed);
		//index.action中会自动加载，所以这里先去掉
		/*lstBed=this.bedService.findList("from Bed t where t.name=? and t.usable=1 order by t.name ASC", bedid);
		if (lstBed.size()>0) {
			DeviceSettings.hasBeds.put(concentratorNo, lstBed.get(0));
		}*/
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		return "{\"success\":true,\"bedid\":\""+bedid+"\"}";
	}
	/*
	 * 璁＄畻鍓╀綑鐢甸噺 by rxz
	 */
	private long getTime(Date datestart){
		long n= Math.abs((datestart.getTime()-(new Date()).getTime())/3600000);
		if(n>48)return 0;
		return 48-n;
	}
	@ResponseBody
	@RequestMapping("/stopwarning.action")
	public String stopwarning(String strmac){
		if(DeviceSettings.lstMacs.contains(strmac)){
			TemperatureDevice temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(strmac);
			temperatureDevice.setWarningOrNot(false);
			return Boolean.TRUE.toString().toLowerCase();	
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	@ResponseBody
	@RequestMapping("/stopwarning4nosign.action")
	public String stopwarning4nosign(String strmac){
		if(DeviceSettings.lstMacs.contains(strmac)){
			TemperatureDevice temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(strmac);
			temperatureDevice.setWarningOrNot4NoSign(false);
			return Boolean.TRUE.toString().toLowerCase();	
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	@ResponseBody
	@RequestMapping("/stopwarning4nopower.action")
	public String stopwarning4nopower(String strmac){
		if(DeviceSettings.lstMacs.contains(strmac)){
			TemperatureDevice temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(strmac);
			temperatureDevice.setWarningOrNot4NoPower(false);
			return Boolean.TRUE.toString().toLowerCase();	
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	@ResponseBody
	@RequestMapping("/stopwarning4openarms.action")
	public String stopwarning4openarms(String strmac){
		if(DeviceSettings.lstMacs.contains(strmac)){
			TemperatureDevice temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(strmac);
			//temperatureDevice.setOpenArmsTime(null);//重置为null会有问题
			temperatureDevice.setWarningOrNot4OpenArms(false);
			temperatureDevice.setIfReNormal4OpenArms(false);
			return Boolean.TRUE.toString().toLowerCase();	
		}
		return Boolean.FALSE.toString().toLowerCase();
	}
	/**
	 * 获取当前各个床位的各项指标数据，并传到前台进行更新
	 * 2018年1月8日20:22:54
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getCurBedsData.action")
	public String getCurBedsData(HttpSession session){
		JSONArray result=new JSONArray();
		try {
			/*if (DeviceSettings.lstBeds.size()==0) {//如果还没有进行初始化则重新查询数据库
				DeviceSettings.lstBeds=this.bedService.findList("from Bed t where t.user.id=? and t.usable=1 order by (t.name+0) ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
			}*/
//			DeviceSettings.lstBeds=this.bedService.findList("from Bed t where t.user.id=? and t.usable=1 order by (t.name+0) ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
			DeviceSettings.lstBeds=this.bedService.findList("from Bed t where t.usable=1 order by (t.name+0) ASC");
			for (Bed bed : DeviceSettings.lstBeds) {
				JSONObject bedJSONObject=new JSONObject();
				/*bed.setUser(null);
				if (bed.getPatient()!=null) {
					bed.getPatient().setUser(null);
					bed.getPatient().setBedUserList(null);
				}*/
				bedJSONObject.put("id", bed.getId());
				bedJSONObject.put("name", bed.getName());
				bedJSONObject.put("status", bed.getStatus());
				bedJSONObject.put("concentratorNo", bed.getConcentratorNo());
				if (!bed.getStatus().equals("empty")) {
					Bed bedTemp=DeviceSettings.hasBeds.get(bed.getConcentratorNo());
					if (null!=bedTemp) {
						bedJSONObject.put("admissionNumber", bed.getPatient().getAdmissionNumber());
						bedJSONObject.put("patientName", bed.getPatient().getName());
						bedJSONObject.put("patientId", bed.getPatient().getId());
						bedJSONObject.put("temperature", bedTemp.getTemperature());
						
						if (null!=bedTemp.getOximetry()) {
							if (bedTemp.getOximetry().getSpo2()<0) {
								bedTemp.getOximetry().setSpo2(0);
							}else if (bedTemp.getOximetry().getSpo2()>100) {
								bedTemp.getOximetry().setSpo2(100);
							}
							if (bedTemp.getOximetry().getPulserate()<0) {
								bedTemp.getOximetry().setPulserate(0);
							}
						}
						bedJSONObject.put("oximetry", bedTemp.getOximetry());
						/*if (bedTemp.getBloodPressure()!=null) {
							new SimpleDateFormat("yyyy-MM-dd HH:mm");
							bedTemp.getBloodPressure().setHighPressure(100);
							bedTemp.getBloodPressure().setLastUpdateTime(new Date());
						}*/
						if (null!=bedTemp.getBloodPressure()&&bedTemp.getBloodPressure().getLowPressure()<0&&bedTemp.getBloodPressure().getLowPressure()!=-1) {
							bedTemp.getBloodPressure().setLowPressure(0);
							bedTemp.getBloodPressure().setHighPressure(0);
						}
						bedJSONObject.put("bloodPressure", bedTemp.getBloodPressure());
						EcgAnalysis ecgAnalysis = DataHandlerManager.getHasDataAynalysis(bed.getConcentratorNo()+BodystmProduct.BodystmECG.ordinal());
						if(bedTemp.getEcg()!=null&&null!=ecgAnalysis){//bedTemp.getEcg().getEcgAnalysis()
							if (bedTemp.getEcg().getHr()<0) {
								bedTemp.getEcg().setHr(0);
							}
//							bedJSONObject.put("ecgChannel", bedTemp.getEcg().getEcgAnalysis().getStrEcgChannel());
							bedJSONObject.put("ecgChannel", ecgAnalysis.channelType.ordinal());
//							bedJSONObject.put("ecgChannel", bedTemp.getEcg().getEcgAnalysis().channelType.ordinal());
							
						}else{
							bedJSONObject.put("ecgChannel", 0);
						}
						bedJSONObject.put("ecg", bedTemp.getEcg());
						//设备状态相关
						bedJSONObject.put("temStatus", (bedTemp.getTemUpdateMs()==-1||(System.currentTimeMillis()-bedTemp.getTemUpdateMs())/60000>=1)?0:1);
						bedJSONObject.put("oxiStatus", (bedTemp.getOxiUpdateMs()==-1||(System.currentTimeMillis()-bedTemp.getOxiUpdateMs())/60000>=1)?0:1);
//						bedJSONObject.put("bloStatus", (bedTemp.getBloUpdateMs()==-1||(System.currentTimeMillis()-bedTemp.getBloUpdateMs())/60000>=1)?0:1);
						bedJSONObject.put("bloStatus", 1);
						bedJSONObject.put("ecgStatus", (bedTemp.getEcgUpdateMs()==-1||(System.currentTimeMillis()-bedTemp.getEcgUpdateMs())/60000>=1)?0:1);
						bedJSONObject.put("respStatus",(bedTemp.getRespUpdateMs()==-1||(System.currentTimeMillis()-bedTemp.getRespUpdateMs())/60000>=1)?0:1);
						
						bedJSONObject.put("rangeStart",bed.getPatient().getRangeStart());
						bedJSONObject.put("rangeEnd",bed.getPatient().getRangeEnd());
						bedJSONObject.put("superHighDegree",bed.getPatient().getSuperHighDegree());
						bedJSONObject.put("spo2LowAlarmValue",bed.getPatient().getSpo2LowAlarmValue());
						bedJSONObject.put("spo2HighAlarmValue",bed.getPatient().getSpo2HighAlarmValue());
						bedJSONObject.put("hrLowAlarmValue",bed.getPatient().getHrLowAlarmValue());
						bedJSONObject.put("hrHighAlarmValue",bed.getPatient().getHrHighAlarmValue());
					}
					
				}
				result.add(bedJSONObject);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//result.addAll(DeviceSettings.lstBeds);
		return result.toString();
	}
	/*
	 * 鑾峰彇鎵�湁搴婁綅鐨勫垪琛�
	 */
	@ResponseBody
	@RequestMapping("/listAll.action")
	public String listAll(HttpSession session) {
        try {
        	java.util.List<Bed> lstBed=null;
        	if (DeviceSettings.lstBeds.size()==0) {
        		lstBed=this.bedService.findList("from Bed t where t.user.id=? and t.usable=1 order by (t.name+0) ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
        		DeviceSettings.lstBeds=lstBed;
			}else{
				lstBed=DeviceSettings.lstBeds;
			}
			//java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.user.id=? and t.usable=1 order by (t.name+0) ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
			if(lstBed==null||lstBed.size()==0) return "{\"total\":0,\"data\":[],\"otherdata:\"[]}";
			JSONArray jSONArray = new JSONArray();
			JSONObject bedJSONObject = null;
			JSONObject personJSONObject = new JSONObject();
			JSONObject personTempJSONObject = null;
			Patient patient=null;
			Temperature temperature=null;
			float[] strTemp4degrees=null; float[] strTemp4degree=null;DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
			List<Temperature> temperatures;
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
			SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdfHAndM = new SimpleDateFormat("HH:mm");
			float theDegreeOfABed=0;//获取到的某个床位的实时温度
			PatientBedUser patientBedUser=null;
			Temperature temperatureLatest=null;//获取剩余电量时使用
			String[] strTimesTemp=null;//临时存放某个床位病人体温数据的时间数据
			Calendar calendar=Calendar.getInstance();
			Date curTime=new Date();
			for (Bed bed : lstBed) {
				bedJSONObject=new JSONObject();
				patient=DeviceSettings.hasDevice4PatientOfBed.get(bed.getId());
				if (patient==null&&bed.getStatus().equals("notempty")) {
					patient = this.patientService.findByBedIdAndEndTimeIsNull(bed
							.getId());
					if(patient!=null)
					DeviceSettings.hasDevice4PatientOfBed.put(bed.getId(), patient);
				}
//				patient = this.patientService.findByBedIdAndEndTimeIsNull(bed.getId());
				if (patient != null) {
					bed.setPatient(patient);
					bed.setStatus("notempty");
					//判断全局变量中是否含有此设备，没有则新建，有则获取,然后获取其中的实时温度最后显示到界面上
					TemperatureDevice temperatureDevice=null;
					//获取实时温度
					boolean ifgetDegree=false;
					if (patient.getEquipNo() != null) {
						//theDegreeOfABed=0;
						/*//判断全局变量中是否含有此设备，没有则新建，有则获取,然后获取其中的实时温度最后显示到界面上
						TemperatureDevice temperatureDevice=null;*/
						if(DeviceSettings.lstMacs.contains(patient.getEquipNo())){
							temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(patient.getEquipNo());
							if(temperatureDevice!=null&&temperatureDevice.getCurrentDegree()>0){
								//bedJSONObject.put("degree",decimalFormat.format(temperatureDevice.getCurrentDegree()));//保留两位小数
								ifgetDegree=true;
								theDegreeOfABed=temperatureDevice.getCurrentDegree();
							}
							else{
								
								temperature = this.temperatureService
										.findLatestByEquipNoAndMeasureTime(
												patient.getEquipNo(),
												patient.getStartTime());
								if (temperature != null) {
									bed.setTemperature(temperature);
									ifgetDegree=true;
									//bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
									theDegreeOfABed=temperature.getMeasureNum();
									temperatureDevice.setCurrentDegree(temperature.getMeasureNum());
								}
							}
						}else{
							//
							DeviceSettings.lstMacs.add(patient.getEquipNo());
							temperatureDevice=new TemperatureDevice();
							temperatureDevice.setStrMac(patient.getEquipNo());
							DeviceSettings.hasDevice.put(patient.getEquipNo(), temperatureDevice);
							temperature = this.temperatureService
									.findLatestByEquipNoAndMeasureTime(
											patient.getEquipNo(),
											patient.getStartTime());
							if (temperature != null) {
								bed.setTemperature(temperature);
								ifgetDegree=true;
								//bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
								theDegreeOfABed=temperature.getMeasureNum();
							}
						}
					}
					
					bedJSONObject.put("listenstate", "listening");
					if(ifgetDegree){//bed.getTiwen()!=null){
						//bedJSONObject.put("degree",bed.getTiwen().getMeasureNumOne());
						//bedJSONObject.put("degree",decimalFormat.format(bed.getTiwen().getMeasureNumOne()));//保留两位小数
						bedJSONObject.put("degree",decimalFormat.format(theDegreeOfABed));//保留两位小数
						//getTime(patient.getListenStartTime())
						
						if(theDegreeOfABed>=patient.getSuperHighDegree()){
							bedJSONObject.put("state", "superhigh");
							if(temperatureDevice.getWarningType()==2){
								temperatureDevice.setWarningOrNot(true);
							}
							temperatureDevice.setWarningType(3);
							
						}else if(theDegreeOfABed>= patient.getRangeEnd()){
							bedJSONObject.put("state", "high");
							if(temperatureDevice.getWarningType()==3){
								if (theDegreeOfABed<patient.getSuperHighDegree()-0.5) {
									temperatureDevice.setWarningType(2);
								}
							}else{
								temperatureDevice.setWarningType(2);
							}
							
						}
						else if(theDegreeOfABed<=patient.getRangeStart()){
							bedJSONObject.put("state", "low");
							//刚佩戴上五分钟后开始报警
							if (temperatureDevice.getFirstDataTime()!=null&&(curTime.getTime()-temperatureDevice.getFirstDataTime().getTime())/1000>=300) {
								temperatureDevice.setWarningType(1);
							}else{
								temperatureDevice.setWarningType(0);
							}
						}
						else{
							bedJSONObject.put("state", "normal");
							temperatureDevice.setWarningType(0);
							if(theDegreeOfABed>patient.getRangeStart()+0.5||theDegreeOfABed<patient.getRangeEnd()-0.5){//报警迟滞性0.3-->0.5
								temperatureDevice.setWarningOrNot(true);
							}
//							temperatureDevice.setWarningOrNot(true);
						}
						bedJSONObject.put("ifWarn",temperatureDevice.isWarningOrNot());
						bedJSONObject.put("warningType",temperatureDevice.getWarningType());
//						if(temperatureDevice.isWarningOrNot4OpenArms()){
//							bedJSONObject.put("warningOrNot4OpenArms", temperatureDevice.isWarningOrNot4OpenArms());
//						}
						bedJSONObject.put("warningOrNot4OpenArms", temperatureDevice.isWarningOrNot4OpenArms());
						bedJSONObject.put("status4OpenArms", temperatureDevice.isStatus4OpenArms());
					}
					
					
					bedJSONObject.put("range", patient.getRangeStart()+"~"+patient.getRangeEnd());
					if(patient.getListenStartTime()!=null&&patient.getListenEndTime()!=null)
					bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime())+"~"+sdf.format(patient.getListenEndTime()));
					else if(patient.getListenStartTime()!=null)bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime()));//patient.getListenStartTime()
					bedJSONObject.put("num", patient.getEquipNo());
					if(patient.getListenStartTime()!=null)
					bedJSONObject.put("surplustime", getTime(patient.getListenStartTime()));
					//获取温度贴片的剩余电量
					bedJSONObject.put("powerNum", temperatureDevice.getPowerNum());
//					temperatureLatest=temperatureService.getLatestTemprature(patient.getEquipNo());
//					if(temperatureLatest!=null){
//						bedJSONObject.put("powerNum", temperatureLatest.getPowerNum());
//					}else{
//						bedJSONObject.put("powerNum", 100);
//					}
					bedJSONObject.put("personinfo", patient.getName()+(patient.getSex()!=null?("-"+patient.getSex()):"")+(patient.getAge()>0?("-"+patient.getAge()+"岁"):""));
					bedJSONObject.put("name", patient.getName());
					bedJSONObject.put("sex", patient.getSex());
					bedJSONObject.put("age", patient.getAge());
					if(patient.getStartTime()!=null)
					bedJSONObject.put("roomtime", sdfTime.format(patient.getStartTime()));//sdfDate

					bedJSONObject.put("patientid", patient.getId());//鑾峰彇鐥呬汉id浠ヤ究鍑洪櫌绛夊悗缁搷浣�
					bedJSONObject.put("num4Correct", patient.getNum4Correct());
					
					
					personTempJSONObject=new JSONObject();
					
					//获取贴片工作状态
					patientBedUser=DeviceSettings.hasDevice4PBUOfMacs.get(patient.getEquipNo());
					if (patientBedUser==null) {
						patientBedUser =patientBedUserDao.getPatientBedUserByPatientAnddBed(patient.getId(), bed.getId());
					}
//					patientBedUser =patientBedUserDao.getPatientBedUserByPatientAnddBed(patient.getId(), bed.getId());
					if(patientBedUser!=null&&patientBedUser.getStatusOfDevice()!=null){
						bedJSONObject.put("deviceStatus", patientBedUser.getStatusOfDevice());
						bedJSONObject.put("warningOrNot4NoSign", temperatureDevice.isWarningOrNot4NoSign());
					}else{
						bedJSONObject.put("deviceStatus", 1);
					}
					//超过50小时的提醒相关
					if(temperatureDevice!=null&&temperatureDevice.getWarningOrNot4NoPower()!=null){//&&temperatureDevice.getWarningOrNot4NoPower()==true
						bedJSONObject.put("nopower", temperatureDevice.getWarningOrNot4NoPower()==true?1:0);
						if (temperature != null&&temperature.getPowerNum()!=1) {
							temperature.setPowerNum(1);
							this.temperatureService.save(temperature);
						}
					}else{
						bedJSONObject.put("nopower", -1);
					}
					/*try {
						temperatures=this.temperatureService
						.find24ByEquipNoAndMeasureTime(
								patient.getEquipNo(),
								patient.getStartTime());
						if(temperatures!=null&&temperatures.size()>0){
							Calendar date=Calendar.getInstance();
							date.setTime(temperatures.get(0).getMeasureTime());
							strTemp4degrees=new float[temperatures.size()];strTemp4degree=new float[temperatures.size()];
							if(temperatures.size()%2==0){
								strTemp4degree=new float[temperatures.size()/2];
							}
							else if(date.get(Calendar.HOUR_OF_DAY)%2==0){
								strTemp4degree=new float[(temperatures.size()+1)/2];
							}
							else{
								strTemp4degree=new float[temperatures.size()/2];
							}
							int countStr=0;
							
							for(int i=0;i<temperatures.size();i++){
								//temperatures.get(i).getMeasureTime().getHours()+
								date.setTime(temperatures.get(i).getMeasureTime());
								if(date.get(Calendar.HOUR_OF_DAY)%2!=0) continue;
								if(i==0||i==1){
									personTempJSONObject.put("times", date.get(Calendar.HOUR_OF_DAY));
								}
								strTemp4degrees[i]=temperatures.get(i).getMeasureNumOne();
								//personTempJSONObject.put("degrees", strTemp4degrees);
								//温度数据保留两位小数
								//strTemp4degree[i]=decimalFormat.format(temperatures.get(i).getMeasureNumOne());
								if(countStr<=strTemp4degree.length-1)
								strTemp4degree[countStr++]=temperatures.get(i).getMeasureNumOne()<34?34:(temperatures.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne());//decimalFormat.format(temperatures.get(i).getMeasureNumOne());
//							personTempJSONObject.put("degrees", strTemp4degree);
							}
							personTempJSONObject.put("degrees", strTemp4degree);

						}else{
							personTempJSONObject.put("times", null);
							personTempJSONObject.put("degrees", null);
						}
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/
					//personJSONObject.put(bed.getName(), personTempJSONObject);
					
					//****************************************************获取新版数据，用于折线图显示*********************************************************************
					/*int maxPointsNum=48;//折线图中最多显示的数据点的数量
					String startTime4chart="";//第一个数据的时间
					int interval=0;//数据获取的间隔，每几个数据获取一个？
					temperatures=this.temperatureService.getAllByEquipNo(patient.getEquipNo());
					if(temperatures!=null&&temperatures.size()>0){
						startTime4chart=sdfTime.format(temperatures.get(0).getMeasureTime());//获取数据的第一条的时间
						if(temperatures.size()<=maxPointsNum){//如果获取的数据少于规定最大数量则直接全部获取
							strTimesTemp=new String[temperatures.size()];
							strTemp4degree=new float[temperatures.size()];
							for(int i=0;i<temperatures.size();i++){
								strTemp4degree[i]=temperatures.get(i).getMeasureNumOne()<34?34:(temperatures.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne());
								strTimesTemp[i]=sdfHAndM.format(temperatures.get(i).getMeasureTime());
							}
							personTempJSONObject.put("degrees4chart", strTemp4degree);
						}else{//如果获取的数据多于规定最大数量则直接全部获取
							interval=temperatures.size()/maxPointsNum;
//						Calendar calendar=Calendar.getInstance();
							calendar.setTime(temperatures.get(temperatures.size()-1).getMeasureTime());
							calendar.add(Calendar.MINUTE, -5*interval*maxPointsNum);
							startTime4chart=sdfTime.format(calendar.getTime());//获取数据的第一条的时间						
							strTemp4degree=new float[maxPointsNum];
							strTimesTemp=new String[maxPointsNum];
							int countStr=0;
							for(int i=0;i<temperatures.size();i=i+interval){
								if(countStr<=strTemp4degree.length-1){
									strTemp4degree[countStr]=temperatures.get(i).getMeasureNumOne()<34?34:(temperatures.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne());
									strTimesTemp[countStr++]=sdfHAndM.format(temperatures.get(i).getMeasureTime());
								}
								
							}
							//personTempJSONObject.put("degrees4chart", strTemp4degree);
						}
						personTempJSONObject.put("degrees4chart", strTemp4degree);
						personTempJSONObject.put("times4chart", strTimesTemp);
						personTempJSONObject.put("startTime4chart", startTime4chart);
					}else{
						personTempJSONObject.put("times4chart", null);
						personTempJSONObject.put("startTime4chart", null);
						personTempJSONObject.put("degrees4chart", null);
					}*/
					//******************************************************************************************************************************
					personJSONObject.put(bed.getName(), personTempJSONObject);
				}
				else{
					bed.setStatus("empty");

				}
				bedJSONObject.put("bedid", bed.getName());
				bedJSONObject.put("idofbed", bed.getId());
				bedJSONObject.put("bedstate", bed.getStatus());
				jSONArray.add(bedJSONObject);

			}
			//获取未识别设备列表信息
			JSONObject json=new JSONObject();
			//Float[] arr=new Float[DeviceSettings.lstMacs4NoPatients.size()];
			List<Float> lstT=new ArrayList<Float>();
			json.put("expmacs", DeviceSettings.lstMacs4NoPatients.toArray());
			for (String mac : DeviceSettings.lstMacs4NoPatients) {
				if (DeviceSettings.hasMacTem4NoPatient.contains(mac)) {
					lstT.add(DeviceSettings.hasMacTem4NoPatient.get(mac));
				}else{
					lstT.add(-1f);
				}
				
			}
			json.put("exptemps",lstT);
			return "{\"total\":"+lstBed.size()+",\"data\":"+jSONArray.toString()+",\"otherdata\":"+personJSONObject.toString()+",\"expData\":"+json.toString()+"}";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	@ResponseBody
	@RequestMapping("/getDegreeByMac.action")
	public String getDegreeByMac(String strMac,String type4Time,HttpSession session) {
		try {
			float[] strTemp4degree=null;
			JSONObject personTempJSONObject = new JSONObject();
			List<Temperature> temperatures=null;
			SimpleDateFormat sdfHAndM = new SimpleDateFormat("HH:mm");
			SimpleDateFormat sdfH = new SimpleDateFormat("HH:00");
			SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdfDateH = new SimpleDateFormat("MM-dd HH:00");
			SimpleDateFormat sdfDateH2 = new SimpleDateFormat("     HH:00");//用于同一天日期不重复显示
			SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd");
			DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
			String[] strTimesTemp=null;//临时存放某个床位病人体温数据的时间数据
			String[] strDateHsTemp=null;
			Calendar calendar=Calendar.getInstance();
			//
			int datacount=0;
			//续贴功能相关
			List<Temperature> temperaturesTEmp=null;
			List<PatientEquip> lstPE=patientEquipService.getPatientEquipByMac(strMac);
			String patientID="";
			if(lstPE!=null&&lstPE.size()>0){
				patientID=lstPE.get(0).getPatientID();
			}
			List<PatientEquip> lstPE2=null;
			if(patientID.length()>0){
				lstPE2=patientEquipService.getPatientEquipByPatient(patientID);
				if(lstPE2!=null){
					temperatures=new ArrayList<Temperature>();
					/*for(int j=0;j<lstPE2.size();j++){
						temperaturesTEmp=this.temperatureService.find24ByEquipNoAndMeasureTime(lstPE2.get(j).getEquipNo());
						if(temperaturesTEmp!=null&&temperaturesTEmp.size()>0)
						temperatures.addAll(temperaturesTEmp);
					}*/
					String strMacs="";
					for(int j=0;j<lstPE2.size();j++){
						strMacs+="'"+lstPE2.get(j).getEquipNo()+"',";
					}
					if(strMacs.length()>0){
						strMacs=strMacs.substring(0,strMacs.length()-1);
						//temperatures = this.temperatureService.find24ByMacsAndMeasureTime(strMacs);
						//根据用户设置的时间间隔类型获取温度数据
//						temperatures = this.temperatureService.findAllByMacs(strMacs);
						int flag=0;
						switch (type4Time) {
						case "5":
							flag = 1;
							temperatures = this.temperatureService.findAllByMacs(strMacs);
							sdfH = new SimpleDateFormat("HH:mm");
							sdfDateH = new SimpleDateFormat("MM-dd HH:mm");
							sdfDateH2= new SimpleDateFormat("HH:mm");
							break;
						case "10":
							flag = 2;
							temperatures = this.temperatureService.findAllByMacs(strMacs);
							sdfH = new SimpleDateFormat("HH:mm");
							sdfDateH = new SimpleDateFormat("MM-dd HH:mm");
							sdfDateH2= new SimpleDateFormat("HH:mm");
							break;
						case "30":
							flag = 6;
							temperatures = this.temperatureService.findAllByMacs(strMacs);
							sdfH = new SimpleDateFormat("HH:mm");
							sdfDateH = new SimpleDateFormat("MM-dd HH:mm");
							sdfDateH2= new SimpleDateFormat("HH:mm");
							break;
						case "60":
							flag = 12;
							temperatures = this.temperatureService.find24ByMacsAndMeasureTime(strMacs);
							sdfH = new SimpleDateFormat("HH:00");
							sdfDateH = new SimpleDateFormat("MM-dd HH:00");
							sdfDateH2= new SimpleDateFormat("HH:00");
							break;
						case "120":
							flag = 24;
							temperatures = this.temperatureService.find24ByMacsAndMeasureTime(strMacs);
							sdfH = new SimpleDateFormat("HH:00");
							sdfDateH = new SimpleDateFormat("MM-dd HH:00");
							sdfDateH2= new SimpleDateFormat("HH:00");
							break;
						default:
							flag = 1;
							break;
						}
						int noTemp=0;
						if(flag<12){
							for(int k=0;k<temperatures.size();k++){
								if(noTemp++%flag!=0)temperatures.remove(k--);
							}
						}else if(flag==24){
							Calendar dateTemp=Calendar.getInstance();
							for(int k=0;k<temperatures.size();k++){
								dateTemp.setTime(temperatures.get(k).getMeasureTime());
								if(dateTemp.get(Calendar.HOUR_OF_DAY)%2==1)
								temperatures.remove(k--);
							}
						}
						
					}
				}
			}
			//temperatures=this.temperatureService.find24ByEquipNoAndMeasureTime(strMac);
					if(temperatures!=null&&temperatures.size()>0){
						Calendar date=Calendar.getInstance();
						/*for(int i=0;i<temperatures.size();i++){
							date.setTime(temperatures.get(i).getMeasureTime());
							if(date.get(Calendar.HOUR_OF_DAY)%2==0)datacount++;
						}
						strTemp4degree=new float[datacount];
						strTimesTemp=new String[datacount];
						strDateHsTemp=new String[datacount];*///20160617体温表格时间间隔由用户设置
						strTemp4degree=new float[temperatures.size()];
						strTimesTemp=new String[temperatures.size()];
						strDateHsTemp=new String[temperatures.size()];
						/*date.setTime(temperatures.get(0).getMeasureTime());
						strTemp4degree=new float[temperatures.size()];
						strTimesTemp=new String[temperatures.size()];
						if(temperatures.size()%2==0){
							strTemp4degree=new float[temperatures.size()/2];
							strTimesTemp=new String[temperatures.size()/2];
						}
						else if(date.get(Calendar.HOUR_OF_DAY)%2==0){
							strTemp4degree=new float[(temperatures.size()+1)/2];
							strTimesTemp=new String[(temperatures.size()+1)/2];
						}
						else{
							strTemp4degree=new float[temperatures.size()/2];
							strTimesTemp=new String[temperatures.size()/2];
						}*/
						int countStr=0;
						String strDateTemp="";
						List<List<Float>> lstStrTemp4degrees=new ArrayList<List<Float>>();
						List<List<String>> lstStrTimesTemps=new ArrayList<List<String>>();
						List<Float> lstdegrees=null; 
						List<String> lsttimes=null; 
						List<String> dates=new ArrayList<String>();
						for(int i=0;i<temperatures.size();i++){
							//temperatures.get(i).getMeasureTime().getHours()+
							/*date.setTime(temperatures.get(i).getMeasureTime());
							if(date.get(Calendar.HOUR_OF_DAY)%2!=0) continue;*///20160617体温表格时间间隔由用户设置
							if(i==0||i==1){
								personTempJSONObject.put("times", date.get(Calendar.HOUR_OF_DAY));
							}
							//strTemp4degrees[i]=temperatures.get(i).getMeasureNumOne();
							//personTempJSONObject.put("degrees", strTemp4degrees);
							//温度数据保留两位小数
							//strTemp4degree[i]=decimalFormat.format(temperatures.get(i).getMeasureNumOne());
							if(countStr<=strTemp4degree.length-1){
								strTemp4degree[countStr]=temperatures.get(i).getMeasureNum()<15?15:(temperatures.get(i).getMeasureNum()>45?45:temperatures.get(i).getMeasureNum());//decimalFormat.format(temperatures.get(i).getMeasureNumOne());
								strTimesTemp[countStr]=sdfH.format(temperatures.get(i).getMeasureTime());
								if(strDateTemp.length()==0){
									lstdegrees=new ArrayList<Float>();
									lsttimes=new ArrayList<String>(); 
									lstStrTemp4degrees.add(lstdegrees);
									lstStrTimesTemps.add(lsttimes);
									lstdegrees.add(temperatures.get(i).getMeasureNum()<15?15:(temperatures.get(i).getMeasureNum()>45?45:temperatures.get(i).getMeasureNum()));
									lsttimes.add(sdfH.format(temperatures.get(i).getMeasureTime()));							
									strDateTemp=sdfDate.format(temperatures.get(i).getMeasureTime());
									dates.add(strDateTemp);
									strDateHsTemp[countStr++]=sdfDateH.format(temperatures.get(i).getMeasureTime());
								}else{
									if(strDateTemp.equals(sdfDate.format(temperatures.get(i).getMeasureTime()))){
										lstdegrees.add(temperatures.get(i).getMeasureNum()<15?15:(temperatures.get(i).getMeasureNum()>45?45:temperatures.get(i).getMeasureNum()));
										lsttimes.add(sdfH.format(temperatures.get(i).getMeasureTime()));
										strDateHsTemp[countStr++]=sdfDateH2.format(temperatures.get(i).getMeasureTime());
									}else{
										lstdegrees=new ArrayList<Float>();
										lsttimes=new ArrayList<String>(); 
										lstStrTemp4degrees.add(lstdegrees);
										lstStrTimesTemps.add(lsttimes);
										lstdegrees.add(temperatures.get(i).getMeasureNum()<15?15:(temperatures.get(i).getMeasureNum()>45?45:temperatures.get(i).getMeasureNum()));
										lsttimes.add(sdfH.format(temperatures.get(i).getMeasureTime()));
										strDateTemp=sdfDate.format(temperatures.get(i).getMeasureTime());
										dates.add(strDateTemp);
										strDateHsTemp[countStr++]=sdfDateH.format(temperatures.get(i).getMeasureTime());
									}
									
								}
								//strDateHsTemp[countStr++]=sdfDateH.format(temperatures.get(i).getMeasureTime());
							}
							
						}
						//for()
						personTempJSONObject.put("degrees4chart", lstStrTemp4degrees);//strTemp4degree
						personTempJSONObject.put("times4chart", lstStrTimesTemps);//strTimesTemp
						personTempJSONObject.put("dhs4chart", strDateHsTemp);
						personTempJSONObject.put("dates4Chart", dates);

					}else{
						personTempJSONObject.put("degrees4chart", null);
						personTempJSONObject.put("times4chart", null);
						personTempJSONObject.put("dhs4chart", null);
						personTempJSONObject.put("dates4Chart", null);
					}
			//****************************************************获取新版数据，用于折线图显示*********************************************************************
			/*int maxPointsNum=16;//折线图中最多显示的数据点的数量
			String startTime4chart="";//第一个数据的时间
			int interval=0;//数据获取的间隔，每几个数据获取一个？
			temperatures=this.temperatureService.getAllByEquipNo(strMac);
			if(temperatures!=null&&temperatures.size()>0){
				startTime4chart=sdfTime.format(temperatures.get(0).getMeasureTime());//获取数据的第一条的时间
				if(temperatures.size()<=maxPointsNum){//如果获取的数据少于规定最大数量则直接全部获取
					strTimesTemp=new String[temperatures.size()];
					strTemp4degree=new float[temperatures.size()];
					for(int i=0;i<temperatures.size();i++){
						strTemp4degree[i]=temperatures.get(i).getMeasureNumOne()<34?34:(temperatures.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne());
						strTimesTemp[i]=sdfHAndM.format(temperatures.get(i).getMeasureTime());
					}
					personTempJSONObject.put("degrees4chart", strTemp4degree);
				}else{//如果获取的数据多于规定最大数量则直接全部获取
					interval=temperatures.size()/maxPointsNum;
//			Calendar calendar=Calendar.getInstance();
					calendar.setTime(temperatures.get(temperatures.size()-1).getMeasureTime());
					calendar.add(Calendar.MINUTE, -5*interval*maxPointsNum);
					startTime4chart=sdfTime.format(calendar.getTime());//获取数据的第一条的时间						
					//strTemp4degree=new float[maxPointsNum];
					//strTimesTemp=new String[maxPointsNum];
					strTemp4degree=new float[(temperatures.size()-1)/(interval+1)+1];
					strTimesTemp=new String[maxPointsNum];
					int countStr=0;
					for(int i=0;i<temperatures.size();i=i+interval+1){//i+interval
						if(countStr<=strTemp4degree.length-1){
							strTemp4degree[countStr]=temperatures.get(i).getMeasureNumOne()<34?34:(temperatures.get(i).getMeasureNumOne()>42?42:temperatures.get(i).getMeasureNumOne());
							strTimesTemp[countStr++]=sdfHAndM.format(temperatures.get(i).getMeasureTime());
						}else{
							break;
						}
						
					}
					//personTempJSONObject.put("degrees4chart", strTemp4degree);
				}
				if(strTimesTemp.length>16){
					interval=strTimesTemp.length/16;
					int countNum=0;
					for(int i=1;i<strTimesTemp.length;i++){
						if(countNum<interval){
							strTimesTemp[i]="";
							countNum++;
						}
						else{
							countNum=0;
						}
						
					}
				}
				personTempJSONObject.put("degrees4chart", strTemp4degree);
				personTempJSONObject.put("times4chart", strTimesTemp);
				personTempJSONObject.put("startTime4chart", startTime4chart);
			}else{
				personTempJSONObject.put("times4chart", null);
				personTempJSONObject.put("startTime4chart", null);
				personTempJSONObject.put("degrees4chart", null);
			}*/
			return personTempJSONObject.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		//******************************************************************************************************************************
	}
	@ResponseBody
	@RequestMapping("/listAll4Patients.action")
	public String listAll4Patients(Page<Patient> page,HttpSession session) {
        try {
        	page.setOrder(Page.DESC);
    		page.setOrderBy("startTime");
    		Page<Patient> pagePatient = this.patientService.findByPage(page,Restrictions.eq("user.id", ((TUser)session.getAttribute(UserContext.USER_ATTR)).getId()));
    		List<Patient> lstPatient=pagePatient.getResult();
    		//List<Patient> lstPatient=this.patientService.findList("from Patient t where t.user.id=? order by t.startTime DESC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
        	if(lstPatient.size()==0) return "{\"total\":0,\"data\":[],\"otherdata:\"[]}";
        	/*java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.user.id=? order by t.name ASC",((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
			if(lstBed.size()==0) return "{\"total\":0,\"data\":[],\"otherdata:\"[]}";*/
			JSONArray jSONArray = new JSONArray();
			JSONObject bedJSONObject = null;
			JSONObject personJSONObject = new JSONObject();
			JSONObject personTempJSONObject = null;
			//Patient patient=null;
			Bed bed=null;
			Temperature temperature=null;
			float[] strTemp4degrees=null; float[] strTemp4degree=null;DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
			List<Temperature> temperatures;
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
			SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdfHAndM = new SimpleDateFormat("HH:mm");
			float theDegreeOfABed=0;//获取到的某个床位的实时温度
			PatientBedUser patientBedUser=null;
			Temperature temperatureLatest=null;//获取剩余电量时使用
			String[] strTimesTemp=null;//临时存放某个床位病人体温数据的时间数据
			Calendar calendar=Calendar.getInstance();
			Date curTime=new Date();
			for (Patient patient : lstPatient) {
				bedJSONObject=new JSONObject();
//				bed=patient.getBed();2018年1月8日23:21:54
				if (patient != null) {
					//bed.setPatient(patient);
					//bed.setStatus("notempty");
					//判断全局变量中是否含有此设备，没有则新建，有则获取,然后获取其中的实时温度最后显示到界面上
					TemperatureDevice temperatureDevice=null;
					//获取实时温度
					boolean ifgetDegree=false;
					if (patient.getEquipNo() != null) {
						/*//判断全局变量中是否含有此设备，没有则新建，有则获取,然后获取其中的实时温度最后显示到界面上
						TemperatureDevice temperatureDevice=null;*/
						if(DeviceSettings.lstMacs.contains(patient.getEquipNo())){
							temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(patient.getEquipNo());
							if(temperatureDevice!=null&&temperatureDevice.getCurrentDegree()>0){
								//bedJSONObject.put("degree",decimalFormat.format(temperatureDevice.getCurrentDegree()));//保留两位小数
								ifgetDegree=true;
								theDegreeOfABed=temperatureDevice.getCurrentDegree();
							}
							else{
								
								temperature = this.temperatureService
										.findLatestByEquipNoAndMeasureTime(
												patient.getEquipNo(),
												patient.getStartTime());
								if (temperature != null) {
									bed.setTemperature(temperature);
									ifgetDegree=true;
									//bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
									theDegreeOfABed=temperature.getMeasureNum();
								}
							}
						}else{
							//
							DeviceSettings.lstMacs.add(patient.getEquipNo());
							temperatureDevice=new TemperatureDevice();
							temperatureDevice.setStrMac(patient.getEquipNo());
							DeviceSettings.hasDevice.put(patient.getEquipNo(), temperatureDevice);
							temperature = this.temperatureService
									.findLatestByEquipNoAndMeasureTime(
											patient.getEquipNo(),
											patient.getStartTime());
							if (temperature != null) {
								bed.setTemperature(temperature);
								ifgetDegree=true;
								//bedJSONObject.put("degree", (float)(Math.round(temperature.getMeasureNumOne()*10))/10);
								theDegreeOfABed=temperature.getMeasureNum();
							}
						}
					}
					
					bedJSONObject.put("listenstate", "listening");
					if(ifgetDegree){//bed.getTiwen()!=null){
						//bedJSONObject.put("degree",bed.getTiwen().getMeasureNumOne());
						//bedJSONObject.put("degree",decimalFormat.format(bed.getTiwen().getMeasureNumOne()));//保留两位小数
						bedJSONObject.put("degree",decimalFormat.format(theDegreeOfABed));//保留两位小数
						//getTime(patient.getListenStartTime())
						if(theDegreeOfABed>=patient.getSuperHighDegree()){
							bedJSONObject.put("state", "superhigh");
							if(temperatureDevice.getWarningType()==2){
								temperatureDevice.setWarningOrNot(true);
							}
							temperatureDevice.setWarningType(3);
							
						}else if(theDegreeOfABed>= patient.getRangeEnd()){
							bedJSONObject.put("state", "high");
							if(temperatureDevice.getWarningType()==3){
								if (theDegreeOfABed<patient.getSuperHighDegree()-0.3) {
									temperatureDevice.setWarningType(2);
								}
							}else{
								temperatureDevice.setWarningType(2);
							}	
						}
						else if(theDegreeOfABed<=patient.getRangeStart()){
							bedJSONObject.put("state", "low");
							//刚佩戴上五分钟后开始报警
							if (temperatureDevice.getFirstDataTime()!=null&&(curTime.getTime()-temperatureDevice.getFirstDataTime().getTime())/1000>=300) {
								temperatureDevice.setWarningType(1);
							}else{
								temperatureDevice.setWarningType(0);
							}
						}
						else{
							bedJSONObject.put("state", "normal");
							temperatureDevice.setWarningType(0);
							if(theDegreeOfABed>patient.getRangeStart()+0.3||theDegreeOfABed<patient.getRangeEnd()-0.3){//报警迟滞性
								temperatureDevice.setWarningOrNot(true);
							}
						}
						bedJSONObject.put("ifWarn",temperatureDevice.isWarningOrNot());
						bedJSONObject.put("warningType",temperatureDevice.getWarningType());
						bedJSONObject.put("warningOrNot4OpenArms", temperatureDevice.isWarningOrNot4OpenArms());					
					}
					
					
					bedJSONObject.put("range", patient.getRangeStart()+"~"+patient.getRangeEnd());
					if(patient.getListenStartTime()!=null&&patient.getListenEndTime()!=null)
					bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime())+"~"+sdf.format(patient.getListenEndTime()));
					else if(patient.getListenStartTime()!=null)bedJSONObject.put("listentime", sdf.format(patient.getListenStartTime()));//patient.getListenStartTime()
					bedJSONObject.put("num", patient.getEquipNo());
					if(patient.getListenStartTime()!=null)
					bedJSONObject.put("surplustime", getTime(patient.getListenStartTime()));
					//获取温度贴片的剩余电量
					temperatureLatest=temperatureService.getLatestTemprature(patient.getEquipNo());
					if(temperatureLatest!=null){
						bedJSONObject.put("powerNum", temperatureLatest.getPowerNum());
					}else{
						bedJSONObject.put("powerNum", 100);
					}
					bedJSONObject.put("personinfo", patient.getName()+(patient.getSex()!=null?("-"+patient.getSex()):"")+(patient.getAge()>0?("-"+patient.getAge()+"岁"):""));
					bedJSONObject.put("name", patient.getName());
					bedJSONObject.put("sex", patient.getSex());
					bedJSONObject.put("age", patient.getAge());
					if(patient.getStartTime()!=null)
					bedJSONObject.put("roomtime", sdfTime.format(patient.getStartTime()));//sdfDate
					bedJSONObject.put("patientid", patient.getId());//鑾峰彇鐥呬汉id浠ヤ究鍑洪櫌绛夊悗缁搷浣�
					bedJSONObject.put("num4Correct", patient.getNum4Correct());
					
					
					personTempJSONObject=new JSONObject();
					
					//获取贴片工作状态
					patientBedUser =patientBedUserDao.getPatientBedUserByPatientAnddBed(patient.getId(), bed.getId());
					if(patientBedUser!=null&&patientBedUser.getStatusOfDevice()!=null){
						bedJSONObject.put("deviceStatus", patientBedUser.getStatusOfDevice());
						bedJSONObject.put("warningOrNot4NoSign", temperatureDevice.isWarningOrNot4NoSign());
					}else{
						bedJSONObject.put("deviceStatus", 1);
					}
					//超过50小时的提醒相关
					if(temperatureDevice!=null&&temperatureDevice.getWarningOrNot4NoPower()!=null&&temperatureDevice.getWarningOrNot4NoPower()==true){
						bedJSONObject.put("nopower", 1);
					}else{
						
					}
					personJSONObject.put(bed.getName(), personTempJSONObject);
				}
				else{
					//bed.setStatus("empty");

				}
				bedJSONObject.put("bedid", bed.getName());
				bedJSONObject.put("idofbed", bed.getId());
				bedJSONObject.put("bedstate", bed.getStatus());
				jSONArray.add(bedJSONObject);

			}
			return "{\"total\":"+lstPatient.size()+",\"data\":"+jSONArray.toString()+",\"otherdata\":"+personJSONObject.toString()+"}";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/show.action", produces = { "application/json;charset=UTF-8" })
	public String show(String id) {
		Bed bed = this.bedService.getEntity(id);
		String data = "\"\"";
		if (bed != null && bed.getPatient() != null) {
			data = String.format("{\"equipNo\":\"%s\",\"name\":\"%s\",\"id\":\"%s\"}", bed.getPatient().getEquipNo(),
					bed.getPatient().getName(), bed.getPatient().getId());
		}
		EasyUiMessage message = new EasyUiMessage();
		message.setData(data);
		return message.toString();
	}

	@ResponseBody
	@RequestMapping("/update.action")
	public String update(Patient patient, String startTimeStr, String endTimeStr) {
		if (StringUtils.isNotBlank(startTimeStr)) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			try {
				patient.setStartTime(format.parse(startTimeStr));
			} catch (ParseException e) {
				patient.setStartTime(new Date());
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.patientService.saveEntity(patient);
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		return Boolean.TRUE.toString().toLowerCase();
	}

	@ResponseBody
	@RequestMapping("/delete.action")
	public String delete(Bed bed) {
		this.bedService.deleteEntity(bed);
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		return new EasyUiMessage().toString();
	}
	@ResponseBody
	@RequestMapping("/deleteByName.action")
	public String deleteByName(String bedid,HttpSession session) {
//		java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.id=? and t.user.id=?", bedid,((TUser)session.getAttribute(UserContext.USER_ATTR)).getId());
		java.util.List<Bed> lstBed=this.bedService.findList("from Bed t where t.id=?", bedid);
		if(lstBed.size()>0) {
			Bed bed=lstBed.get(0);
			//Patient patient = this.patientService.findByBedIdAndEndTimeIsNull(bed.getId());
//			if(patient!=null){
//				this.patientBedUserService.deleteByBedIdAndPatientId(bed.getId(),patient.getId());
//				patientEquipService.deleteByPatientId(patient.getId());//删除病人贴片关系表数据 20160726
//				this.patientService.deleteByBedId(bed.getId());
//			}
			//20160817 删除病人即改变下病床的状态
			bed.setUsable(0);
			bed.setStatus("empty");
			this.bedService.saveEntity(bed);
			DeviceSettings.hasBeds.remove(bed.getConcentratorNo());
			Patient patient = this.patientService.findByBedIdAndEndTimeIsNull(bed.getId());
			if(patient!=null){
				patient.setEndTime(new Date());
				//2018年1月8日23:22:55
				/*patient.getBed().setStatus("empty");
				patientService.saveEntity(patient);
				PatientBedUser pbu=patientBedUserService.getPatientBedUserByPatientAnddBed(patient.getId(), patient.getBed().getId());
				pbu.setStatus(0);
				pbu.setStatusOfDepartment(0);
				patientBedUserService.saveEntity(pbu);
				//删除出院病人在list中的mac地址
				if (DeviceSettings.lstMacs4CurrentPatients.contains(pbu.getPatient().getEquipNo())) {
					DeviceSettings.lstMacs4CurrentPatients.remove(pbu.getPatient().getEquipNo());
				}*/ 
			}
			
			//******************
			/*List<Patient> lstPatient=this.patientService.findList("from Patient t where t.bed.id=?",bedid);
			for (Patient patient : lstPatient) {
				this.patientBedUserService.deleteByBedIdAndPatientId(bed.getId(),patient.getId());
				patientEquipService.deleteByPatientId(patient.getId());//删除病人贴片关系表数据 20160726	
			}
			this.patientService.deleteByBedId(bed.getId());
			
			this.bedService.deleteByIdofBedbysql(bed.getId());*/
			//this.bedService.deleteEntity(bed);//用这种方式会出现问题：上边两个都删除了，但是是事务型的，用这种方式，bed表认为还没删除以上数据，会出现冲突
		}
		//清空内存中缓存的数据
		DeviceSettings.clearBedPatientData();
		return new EasyUiMessage().toString();
	}
	//2018年3月8日23:54:57
	@ResponseBody
	@RequestMapping("/changeEcgChannel.action")
	public void changeEcgChannel(String mac,int channelType) {
		DataHandlerManager.updateEcgChannelType(mac, EcgChannel.valueOf(channelType));
	}
	@RequestMapping("/patientOutBed.action")
	@ResponseBody
	public String patientOutBed(String bedId, Model model) {
		Bed bed=this.bedService.getEntity(bedId);
		if (bed==null||bed.getStatus().equals("empty")) {
			return Boolean.FALSE.toString().toLowerCase();
		}
		bed.getPatient().setListenEndTime(new Date());
		bed.setStatus("empty");
		bedService.saveEntity(bed);
		//清空内存中缓存的数据
//		DeviceSettings.clearBedPatientData();
		return Boolean.TRUE.toString().toLowerCase();
	}
}